const Activity = require('../models/activity');
const formidable = require('formidable');
const fs = require("fs");
var jsonWrite = function (res, result) {
  if (typeof result === 'undefined') {
    res.json({
      code: 1,
      msg: '操作失败'
    });
  } else {
    res.json({
      code: 0,
      msg: '操作成功',
      data: result,

    });
  }
};

exports.Upload = function (req, res) {
  let form = req.body.form;

  Activity.insertMany({
    title: form.title,
    describe: form.describe,
    contect: form.contect,
    requirement: form.requirement,
    area: form.area,
    type: form.type,
    phone: form.phone,
    address: form.address,
    publisher: form.user,
    starttime: form.starttime,
    endtime: form.endtime,
    contector: form.contector,
  }, (err, result) => {
    if (result) {
      req.session.activity = result;
      jsonWrite(res, result);
    }
    if (err) {
      jsonWrite(res, result);
    }
  })
}

exports.Getact = function (req, res) {
  Activity.find({}, (err, result) => {
    if (result) {
      for (let j = 0; j < result.length; j++) {
        result[j].pic = 'http://localhost:3000/' + result[j].pic.slice(7);
        if (new Date(result[j].endtime).getTime() <= Date.now()) { //检测活动结束日期是否早于当前日期，如是修改活动状态
          Activity.updateMany({
            _id: result[j]._id
          }, {
              $set: {
                status: 1
              }
            }, (err, done) => {
              if (err) {
                console.log(err)
              }
              if (done) {
                return;
              }
            });
        }
      }
      jsonWrite(res, result)
    }
    if (err) {
      jsonWrite(res, err)
    }
  })
}

exports.Getactdetail = function (req, res) {
  Activity.findById(req.query.id, (err, result) => {
    if (result) {
      result.pic = 'http://localhost:3000/' + result.pic.slice(7);
      jsonWrite(res, result)
    }
  })
}

exports.Uploadpic = function (req, res) {
  let formParse = new formidable.IncomingForm();
  let uploadUrl = './public/images/pic';
  if (!fs.existsSync(uploadUrl)) {
    fs.mkdirSync(uploadUrl);
  }
  formParse.uploadDir = uploadUrl; //缓存地址  
  formParse.keepExtensions = true; //是否包含文件后缀  
  let files = [];
  // 文件都将保存在files数组中  
  formParse.on('file', function (field, file) {
    files.push([field, file]);
  })
  formParse.parse(req, function (error, fields, files) {
    if (error) {
      jsonWrite(res, err)
      return;
    }
    if (files) {
      Activity.update({
        _id: req.session.activity[0]._id
      }, {
          pic: files.file.path
        }, (err, result) => {
          if (err) {
            jsonWrite(res, err)
          }
          if (result) {
            jsonWrite(res, result)
          }
        });
      return;
    }
    res.end('上传成功');
  });

}

exports.Signup = function (req, res) {
  Activity.update({
    _id: req.body.id
  }, {
      '$push': {
        signlist: {
          username: req.session.user.username,
          status: 0
        }
      }
    }, (err, result) => {
      if (err) {
        jsonWrite(res, err)
      }
      if (result) {
        jsonWrite(res, result)
      }
    })
};


exports.Getmyacts = function (req, res) {
  Activity.find({
    "publisher._id": req.session.user._id
  }, (err, result) => {
    if (err) {
      jsonWrite(res, err)
    }
    if (result) {
      for (let j = 0; j < result.length; j++) { //修改照片地址
        result[j].pic = 'http://localhost:3000/' + result[j].pic.slice(7);
      }
      jsonWrite(res, result)

    }
  })
}

exports.Deleteact = function (req, res) { //删除活动
  Activity.update({
    _id: req.query.id
  }, {
      $set: {
        'status': 2
      }
    }, (err, result) => {
      if (err) {
        jsonWrite(res, err)
      }
      if (result) {
        jsonWrite(res, result)
      }
    })
}
//搜索
exports.Search = function (req, res) {
  var title = req.body.value;
  Activity.find({ title: { $regex: title, $options: "i" } }, function (err, result) {
    if (err) {
      return console.log(err);
    } if (result) {
      return res.send(result);
    }
  })
}

exports.Pass = function (req, res) {
  Activity.update({
    _id: req.body.actid,
    "signlist._id": req.body.applicantid
  }, {
      $set: {
        "signlist.$.status": 1
      }
    }, (err, result) => {
      if (err) {
        jsonWrite(res, err)
      }
      if (result) {
        jsonWrite(res, result)
      }
    });
}
exports.Refuse = function (req, res) {
  Activity.update({
    _id: req.body.actid,
    "signlist._id": req.body.applicantid
  }, {
      $set: {
        "signlist.$.status": 2
      }
    }, (err, result) => {
      if (err) {
        jsonWrite(res, err)
      }
      if (result) {
        jsonWrite(res, result)
      }
    });
}
exports.Getsignedacts = function (req, res) {
  Activity.find({
    "signlist.username": req.session.user.username
  }, (err, result) => {
    if (err) {
      jsonWrite(res, err)
    }
    if (result) {
      for (let j = 0; j < result.length; j++) { //修改照片地址
        result[j].pic = 'http://localhost:3000/' + result[j].pic.slice(7);
      }
      jsonWrite(res, result)
    }
  });
}

//签到
exports.signin = function (req, res) {
  let data = req.body
  Activity.update({
    _id: data.actid,
    "signlist._id": data.actid2
  }, {
      $set: {
        "signlist.0.sign.status": 1,
        "signlist.0.sign.signTime": data.time,
      }
    }, function (err, user) {
      if (err) {
        return console.log(err);
      }
      if (user) {
        console.log(user);
        return res.send('签到成功');
      } else {
        console.log(err);
      }
    });
};

//签退
exports.signout = function (req, res) {
  let data = req.body
  Activity.update({
    _id: data.actid,
  }, {
      $set: {
        status: 1,
      }
    }, function (err, user) {
      if (err) {
        return console.log(err);
      }
      if (user) {
        console.log(user);
        return res.send('签退成功');
      } else {
        console.log(err);
      }
    });
};
exports.Getsignedactsstatus = function (req, res) {
  Activity.find({
    "signlist.username": req.session.user.username
  }, {
    signlist: {
      $elemMatch: {
        username: req.session.user.username
      }
    }
  }, (err, signlist) => {
    if (err) console.log(err)
    if (signlist) {
      jsonWrite(res,signlist)
      console.log(signlist)
    }
  });
}
